<template>
  <div class="main-box">
    <TreeFilter
      v-show="showTree"
      label="name"
      title="区县列表"
      :request-api="getJIKeDepartmentListApi"
      :default-value="initParam.departmentId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getJIKeIndicatorListApi"
        :span-method="objectSpanMethod"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 2, md: 3, lg: 4, xl: 5 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="showTree ? ArrowLeft : ArrowRight" plain @click="changeTree">{{ treeText }}</el-button>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="Phone" @click="openDrawer('【ivr外呼+短信】督办', scope.row)">ivr+短信</el-button>
          <el-button type="primary" link :icon="Promotion" @click="openDrawer('工单督办', scope.row)">工单督办</el-button>
        </template>
      </ProTable>
      <UserDrawer ref="drawerRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="JIKe">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import { useDownload } from "@/hooks/useDownload";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Download, ArrowLeft, Phone, Promotion, ArrowRight } from "@element-plus/icons-vue";
import UserDrawer from "@/views/competition/components/UserDrawer.vue";
import { SendIvrApi } from "@/api/modules/ivr";
import { raceVal } from "@/utils/dict";
import {
  getJIKeDepartmentListApi,
  exportJIKeInfoApi,
  getJIKeIndicatorListApi,
  getJIKeTeamListApi,
  getJIKeThreeLevelApi
} from "@/api/modules/competition";
import { useShareStore } from "@/stores/modules/share";

const shareStore = useShareStore();
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ departmentId: "" });

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.departmentId = val;
};

const showTree = ref(true);
const treeText = computed(() => (showTree.value ? "隐藏列表" : "显示列表"));
const changeTree = () => {
  showTree.value = !showTree.value;
};

onMounted(async () => {
  const res = await getJIKeThreeLevelApi();
  threeLevelType.value = res.data;
});
// 模拟远程加载性别搜索框数据.value
const threeLevelType = ref<any>([]);
const loading = ref(false);
const filterGenderEnum = ref<typeof threeLevelType.value>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = threeLevelType.value.filter(item => item.label.includes(query));
  }, 500);
};
// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  // { type: "index", label: "序号", width: 60 },
  { prop: "一级指标", label: "一级指标", width: 100, showOverflowTooltip: false, fixed: "left" },
  { prop: "二级指标", label: "二级指标", width: 100, showOverflowTooltip: false, fixed: "left" },
  { prop: "三级指标", label: "三级指标", width: 100, showOverflowTooltip: false, fixed: "left" },
  {
    prop: "四级指标",
    label: "四级指标",
    width: 120,
    showOverflowTooltip: false,
    isFilterEnum: false,
    enum: filterGenderEnum,
    search: {
      el: "select",
      label: "指标名称",
      props: { filterable: true, remote: true, reserveKeyword: true, loading, remoteMethod }
    },
    fieldNames: { label: "label", value: "label" },
    fixed: "left"
  },
  { prop: "权重", label: "权重", width: 50 },
  { prop: "时间粒度", label: "时间粒度", width: 60 },
  { prop: "基准值", label: "基准值", width: 70 },
  { prop: "挑战值", label: "挑战值", width: 70 },
  { prop: "1月", label: "1月", width: 80 },
  { prop: "2月", label: "2月", width: 80 },
  { prop: "3月", label: "3月", width: 80 },
  { prop: "4月", label: "4月", width: 80 },
  { prop: "5月", label: "5月", width: 80 },
  { prop: "6月", label: "6月", width: 80 },
  { prop: "7月", label: "7月", width: 80 },
  { prop: "8月", label: "8月", width: 80 },
  { prop: "9月", label: "9月", width: 80 },
  { prop: "10月", label: "10月", width: 80 },
  { prop: "11月", label: "11月", width: 80 },
  { prop: "12月", label: "12月", width: 80 },
  { prop: "网络部责任台席", label: "网络部责任台席", showOverflowTooltip: false, width: 60 },
  { prop: "中台责任人", label: "中台责任人", width: 80 },
  {
    prop: "责任部门",
    label: "责任部门",
    showOverflowTooltip: false,
    width: 60,
    enum: getJIKeTeamListApi,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "teamLabel", value: "teamLabel" }
  },
  { prop: "班组长", label: "班组长", showOverflowTooltip: false, width: 60 },
  { prop: "项目负责人", label: "项目负责人", showOverflowTooltip: false, width: 60 },
  {
    prop: "是否达标",
    label: "是否达标",
    isShow: false,
    enum: raceVal,
    search: {
      el: "select",
      props: { filterable: true },
      defaultValue: shareStore.is_qualify
    },
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 列合并
function objectSpanMethod({ row, column, rowIndex }) {
  //定义需要合并的列字段，有哪些列需要合并，就自定义添加字段即可
  const fields = ["一级指标", "二级指标", "三级指标"];
  // 当前行的数据
  const cellValue = row[column.property];
  // 判断只合并定义字段的列数据
  if (cellValue && fields.includes(column.property)) {
    const prevRow = proTable.value?.tableData[rowIndex - 1]; //上一行数据
    let nextRow = proTable.value?.tableData[rowIndex + 1]; //下一行数据
    // 当上一行的数据等于当前行数据时，当前行单元格隐藏
    if (prevRow && prevRow[column.property] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
      let countRowspan = 1; //用于合并计数多少单元格
      while (nextRow && nextRow[column.property] === cellValue) {
        nextRow = proTable.value?.tableData[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
}

// 导出用户列表
const downloadFile = async () => {
  console.log(proTable.value!.pageable);
  ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(exportJIKeInfoApi, "网络质量竞赛数据", initParam)
  );
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<any> = {}) => {
  const params = {
    title,
    isView: false,
    row: { ...row },
    api: title === "【ivr外呼+短信】督办" ? SendIvrApi : undefined,
    getTableList: proTable.value?.getTableList
  };
  console.log(drawerRef.value);
  drawerRef.value?.acceptParams(params);
};
</script>
